package net.xxcl.kygl.service;

import java.util.List;

import jxl.Cell;
import net.xxcl.kygl.mapper.*;
import net.xxcl.kygl.pojo.*;
import net.xxcl.kygl.util.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional()
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private TitleMapper titleMapper;
    @Autowired
    private SubjectMapper subjectMapper;
    @Autowired
    private DeptMapper deptMapper;

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Transactional(readOnly = true)
    public int countByExample(Criteria example) {
        int count = this.userMapper.countByExample(example);
        logger.debug("count: {}", count);
        return count;
    }

    @Transactional(readOnly = true)
    public User selectByPrimaryKey(Integer id) {
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public List<User> selectByExample(Criteria example) {
        return this.userMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(Integer id) {
        return this.userMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(User record) {
        return this.userMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(User record) {
        return this.userMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(Criteria example) {
        return this.userMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(User record, Criteria example) {
        return this.userMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(User record, Criteria example) {
        return this.userMapper.updateByExample(record, example);
    }

    public int insert(User record) {
        return this.userMapper.insert(record);
    }

    public int insertSelective(User record) {
        this.userMapper.insertSelective(record);
        //改为返回用户编号
        return record.getId();
    }

    /**
     * 增加新用户，同时增加登录信息
     * @param user
     * @param name
     * @param password
     * @return
     */
    public int addUser(User user,String name,String password) {
        this.userMapper.insertSelective(user);
        Login loginInfo = new Login();
        loginInfo.setUserid(user.getId());
        loginInfo.setName(name);
        loginInfo.setPassword(DigestUtils.encodeSHA512Hex(password.getBytes()));
        return this.loginMapper.insert(loginInfo);
    }

    /**
     * 修改用户，同时可修改登录名
     * @param user
     * @param name
     * @return
     */
    public int updateUser(User user,String name) {
        Login loginInfo = new Login();
        loginInfo.setName(name);
        Criteria criteria = new Criteria();
        criteria.put("userid",user.getId());
        this.loginMapper.updateByExampleSelective(loginInfo,criteria);
        return this.userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 登录验证
     * @param name
     * @param password
     * @return
     */
    @Transactional(readOnly = true)
    public int login(String name,String password){
        Criteria criteria = new Criteria();
        criteria.put("name",name);
        List<Login> list = loginMapper.selectByExample(criteria);System.out.println(DigestUtils.encodeSHA512Hex(password.getBytes()));
        if (list.size()>0 &&
                list.get(0).getPassword().equals(DigestUtils.encodeSHA512Hex(password.getBytes()))){
            return list.get(0).getUserid();
        } else {
            return 0;
        }
    }

    /**
     * 获取用户角色id
     * @return
     */
    @Transactional(readOnly = true)
    public List<Integer> getRoleIdsByUserId(Integer userId){
        return userMapper.getRoleIdsByUserId(userId);
    }

    /**
     * 获取用户角色列表
     * @return
     */
    @Transactional(readOnly = true)
    public List<Role> getRolesByUserId(Integer userId){
        return roleMapper.getRolesByUserId(userId);
    }

    /**
     * 注销用户
     * @param ids
     * @return
     */
    public int deleteUser(String ids) {
        String[] str = ids.split(",");
        User user = new User();
        user.setIsusing(false);
        int userid = 0;
        Criteria criteria = new Criteria();
        for(String id:str){
            userid = Integer.parseInt(id);
            user.setId(userid);
            criteria.put("userid",userid);
            this.userMapper.updateByPrimaryKeySelective(user);
            this.loginMapper.deleteByExample(criteria);
        }
        return str.length;
    }

    /**
     * 重置密码
     * @param ids
     * @return
     */
    public int resetPass(String ids,String password) {
        String[] str = ids.split(",");
        Criteria criteria = new Criteria();
        for(String id:str){
            Login login = new Login();
            criteria.put("userid",Integer.parseInt(id));
            login.setPassword(DigestUtils.encodeSHA512Hex(password.getBytes()));
            this.loginMapper.updateByExampleSelective(login,criteria);
        }
        return str.length;
    }

    /**
     * 关联角色
     * @param roleids
     * @param userids
     * @return
     */
    public int glRole(String roleids,String userids){
        String[] useridsStr = userids.split(",");
        String[] roleidsStr = roleids.split(",");
        UserRoleKey userRoleKey = new UserRoleKey();
        for(String useridStr:useridsStr){
            int userid = Integer.parseInt(useridStr);
            //把之前的删除
            userRoleMapper.deleteByUserId(userid);
            for(String roleidStr:roleidsStr){
                int roleid = Integer.parseInt(roleidStr);
                userRoleKey.setUserid(userid);
                userRoleKey.setRoleid(roleid);
                userRoleMapper.insert(userRoleKey);
            }
        }
        return useridsStr.length;
    }

    public Boolean saveExcelRow(Cell[] cells){
        try{
            Criteria criteria = new Criteria();
            User user = new User();
            Login newLogin = new Login();
            String name = cells[0].getContents().trim();
            String username = cells[1].getContents().trim();
            String password = cells[2].getContents().trim();
            if(name.equalsIgnoreCase("") || password.equalsIgnoreCase("") || username.equalsIgnoreCase("")){
                throw new RuntimeException("工号、姓名、密码不能为空");
            }
            criteria.put("name",name);
            //此处查询工号是否已经存在
            if(loginMapper.selectByExample(criteria).size()>0){
                throw new RuntimeException("工号"+name+"已经存在");
            }

            criteria.clear();
            String deptname = cells[3].getContents().trim();
            criteria.put("name",deptname);
            List<Dept> depts = deptMapper.selectByExample(criteria);

            if(depts.size()>0){
                user.setDeptid(depts.get(0).getId());
            } else {
                // 若无该部门
                String parentName = cells[4].getContents().trim();
                if(parentName.equalsIgnoreCase("")){
                    Dept dept = new Dept();
                    dept.setName(deptname);
                    dept.setParentid(1);
                    deptMapper.insertSelective(dept);
                    user.setDeptid(dept.getId());
                } else {
                    criteria.clear();
                    criteria.put("name",parentName);
                    List<Dept> parentDepts = deptMapper.selectByExample(criteria);
                    if(parentDepts.size()>0){
                        Dept dept = new Dept();
                        dept.setName(deptname);
                        dept.setParentid(parentDepts.get(0).getId());
                        deptMapper.insertSelective(dept);
                        user.setDeptid(dept.getId());
                    } else {
                        Dept parentDept = new Dept();
                        parentDept.setName(parentName);
                        parentDept.setParentid(1);
                        deptMapper.insertSelective(parentDept);

                        Dept dept = new Dept();
                        dept.setName(deptname);
                        dept.setParentid(parentDept.getId());
                        deptMapper.insertSelective(dept);
                        user.setDeptid(dept.getId());
                    }
                }
            }


            String titlename = cells[6].getContents().trim();
            if(!titlename.equalsIgnoreCase("")){
                criteria.clear();
                criteria.put("name",titlename);
                List<Title> titles = titleMapper.selectByExample(criteria);
                if(titles.size()>0){
                    user.setTitleid(titles.get(0).getId());
                }
            }


            String subjectname = cells[8].getContents().trim();
            if(!titlename.equalsIgnoreCase("")){
                criteria.clear();
                criteria.put("name",titlename);
                List<Subject> subjects = subjectMapper.selectByExample(criteria);
                if(subjects.size()>0){
                    user.setSubjectid(subjects.get(0).getId());
                }
            }

            String job = cells[5].getContents().trim();
            if(!job.equalsIgnoreCase("")){
                user.setJob(job);
            }

            String sex = cells[7].getContents().trim();
            if(sex.equalsIgnoreCase("男")){
                user.setSex(true);
            } else {
                user.setSex(false);
            }

            String roles = cells[9].getContents().trim();

            user.setUsername(username);
            userMapper.insertSelective(user);
            newLogin.setUserid(user.getId());
            newLogin.setName(name);
            newLogin.setPassword(DigestUtils.encodeSHA512Hex(password.getBytes()));
            loginMapper.insertSelective(newLogin);
            if(!roles.equalsIgnoreCase("")){
                roles.replaceAll("，",",");
                String[] roleNames = roles.split(",");
                criteria.clear();
                UserRoleKey userRoleKey = new UserRoleKey();
                userRoleKey.setUserid(user.getId());
                for(String roleName:roleNames){
                    criteria.put("name",roleName);
                    List<Role> roleList = roleMapper.selectByExample(criteria);
                    if(roleList.size()>0){
                        userRoleKey.setRoleid(roleList.get(0).getId());
                        userRoleMapper.insertSelective(userRoleKey);
                    } else {
                        throw new RuntimeException(roleName+"角色不存在！");
                    }
                }

            }
            return true;
        } catch (RuntimeException e){
            e.printStackTrace();
            throw e;
        }
    }
}